<?php
namespace app\system\controller;

use app\common\model\Parts;

class User extends Common
{
    /**
     * 用户列表
     * @param string $keywords
     * @param int $type
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($keywords='', $type=-1, $pid=0, $shop_id=0)
    {
        $keywords = trim($keywords);
        $str = '?';
        $where = [];
        if (!empty($keywords)) {
            $where['tel|name'] = ['like', "%$keywords%"];
            $str .= 'keywords='.$keywords;
        }
        if ($type != -1) {
            $where['user_type'] = $type;
            $str .= $str != '?' ? '&' : '';
            $str .= 'type='.$type;
        }
        if ($pid > 0) {
            $where['pid'] = $pid;
            $str .= $str != '?' ? '&' : '';
            $str .= 'pid='.$pid;
        }
        if ($shop_id > 0) {
            $where['shop_id'] = $shop_id;
            $str .= $str != '?' ? '&' : '';
            $str .= 'shop_id='.$shop_id;
        }
        $pageconfig['path'] = url($str);

        $userModel = new \app\common\model\User();
        $list = $userModel->selectUser($where, $this->pageSize, $pageconfig);
        foreach ($list as &$v) {
            if ($v['pid'] > 0) {
                $p_user = $userModel->where(['id'=>$v['pid']])->field('name,tel')->find();
                $v['p_user'] = "{$p_user['name']} | {$p_user['tel']}";
            }
            if ($v['user_type'] > 0) {
                if (($v['user_type'] == 2 || $v['user_type'] == 3) && $v['shop_id'] > 0) {
                    $v['shop_title'] = db('shop')->where(['id'=>$v['shop_id']])->value('title');
                }
                $v['has_son'] = $userModel->where(['pid'=>$v['id']])->count();
            } else {
                $v['has_son'] = 0;
            }
        }

        $assign = [
            'list' => $list,
            'typeList' => $this->typeList
        ];
        return $this->fetch($pid > 0 ? 'sons' : 'index', $assign);
    }

    /**
     * 添加编辑用户
     * @param int $id
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function save($id=0) {
        $userModel = new \app\common\model\User();
        if (isAjaxPost()) {
            $data = input('post.');
            $validate = new \app\system\validate\User();
            if (!$validate->check($data, '', $id > 0 ? 'edit' : 'add')) {
                return $this->jsonError($validate->getError());
            }
            if (!empty($data['password'])) {
                $data['password'] = passmd($data['password']);
            } else {
                unset($data['password']);
            }

            unset($data['id']);
            if ($id > 0) {
                if ($userModel->update($data, ['id'=>$id]) !== false) {
                    return $this->jsonSuccess('修改成功');
                } else {
                    return $this->jsonError('修改失败');
                }
            } else {
                $data['add_time'] = time();
                $data['img'] = config('default_user_img');
                if ($uid = $userModel->insertGetId($data)) {
                    $code = $uid.mt_rand(10,99);
                    $userModel->where(['id'=>$uid])->setField('code', $code);
                    $data['id'] = $uid;
                    $data['code'] = $code;
                    //生成邀请二维码
                    saveQrcode($data);
                    return $this->jsonSuccess('添加成功');
                } else {
                    return $this->jsonError('添加失败');
                }
            }
        }

        if ($id > 0) {
            $this->assign('data', $userModel->findUser(['id'=>$id]));
        }
        $this->assign('typeList', $this->typeList);
        $this->assign('puser', $userModel->where(['user_type'=>2, 'id'=>['neq', $id]])->column('id,name,tel', 'id'));
        $this->assign('shop_list', db('shop')->select());

        return $this->fetch();
    }

    /**
     * 删除用户
     * @param $id
     * @return \think\response\Json
     */
    public function del($id)
    {
        if (isAjaxPost()) {
            $id = intval($id);
            if ($id <= 0) {
                return $this->jsonError('删除失败');
            }

            $model = new \app\common\model\User();
            if ($model->where(['id'=>$id])->delete() !== false) {
                @unlink("./qrcode/invite/{$id}.png");
                return $this->jsonSuccess('删除成功');
            } else {
                return $this->jsonError('删除失败');
            }
        }
    }

    /**
     * 批量删除
     * */
    public function delAll()
    {
        if (isAjaxPost()) {
            $post = input('post.');

            if (empty($post['id']) || !is_array($post['id']) || count($post['id']) <= 0) {
                return $this->jsonError('请勾选需要删除的用户！');
            }
            $ids = $post['id'];

            $model = new \app\common\model\User();
            if ($model->where(['id'=>['in', $ids]])->delete() !== false) {
                foreach ($ids as $v) {
                    @unlink("./qrcode/invite/{$v}.png");
                }
                return $this->jsonSuccess('删除成功');
            } else {
                return $this->jsonError('删除失败');
            }
        }
    }

    public function locks($id, $locks)
    {
        if (isAjaxPost()) {
            $id = intval($id);
            $locks = intval($locks);
            if ($id <= 0 || !in_array($locks, [0, 1])) {
                return $this->jsonError('操作失败');
            }

            $manageModel = new \app\common\model\User();
            if ($manageModel->update(['locks' => $locks], ['id' => $id]) !== false) {
                return $this->jsonSuccess('操作成功');
            } else {
                return $this->jsonError('操作失败');
            }
        }
    }

    /**
     * 商家列表
     * @param string $keywords
     * @param int $status
     * @return mixed
     */
    public function business($keywords='', $status=0)
    {
        $keywords = trim($keywords);
        $str = '?';
        $where = [];
        if (!empty($keywords)) {
            $where['title|tel|name'] = ['like', "%$keywords%"];
            $str .= 'keywords='.$keywords;
        }
        if ($status > 0) {
            $where['status'] = $status;
            $str .= $str != '?' ? '&' : '';
            $str .= 'status='.$status;
        }
        $pageconfig['path'] = url($str);

        $userModel = new Business();
        $list = $userModel->getList($where, $this->pageSize, $pageconfig);

        $assign = [
            'list' => $list,
        ];
        return $this->fetch('', $assign);
    }

    /**
     * 删除用户
     * @param $id
     * @return \think\response\Json
     */
    public function business_del($id)
    {
        !isAjaxPost() && die;
        $id = intval($id);
        if ($id <= 0) {
            return $this->jsonError('删除失败');
        }

        $model = new Business();
        if ($model->where(['id'=>$id,'status'=>3])->count() <= 0) {
            return $this->jsonError('删除失败');
        }

        if ($model->where(['id'=>$id])->delete() !== false) {
            return $this->jsonSuccess('删除成功');
        } else {
            return $this->jsonError('删除失败');
        }
    }

    /**
     * 商家审核
     * @param $id
     * @param $state
     * @param string $reason
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function business_examine ($id, $state, $reason='') {
        if (isAjaxPost()) {
            $model = new Business();
            $info = $model->where('id', $id)->find();
            if (empty($info)) {
                return $this->jsonError('信息不存在');
            }
            $info = $info->toArray();
            if ($info['status'] == 1) {
                if ($state == 1) {
                    $data = [
                        'status' => 2,
                    ];
                } elseif ($state == 2) {
                    if (empty($reason)) {
                        return $this->jsonError('请填写拒绝理由');
                    }
                    $data = [
                        'status' => 3,
                        'reason' => $reason,
                    ];
                } else {
                    return $this->jsonError('状态错误');
                }
            } elseif ($info['status'] == 4) {
                if ($state == 1) {
                    $data = [
                        'status' => 2,
                    ];
                } elseif ($state == 2) {
                    if (empty($reason)) {
                        return $this->jsonError('请填写拒绝理由');
                    }
                    $data = [
                        'status' => 5,
                        'reason' => $reason,
                    ];
                } else {
                    return $this->jsonError('状态错误');
                }
            } else {
                return $this->jsonError('状态错误');
            }

            $model->startTrans();
            if ($model->save($data, ['id' => $id]) !== false) {
                if ($state == 1) {
                    //用户类型改为分销商
                    $user_model = new \app\common\model\User();
                    if ($user_model->where(['id'=>$info['user_id']])->setField('user_type', 1) === false) {
                        $model->rollback();
                        return $this->jsonError('操作失败');
                    }
                }
                $model->commit();
                return $this->jsonSuccess('操作成功');
            } else {
                return $this->jsonError('操作失败');
            }
        }
    }
}